from rest_framework import serializers

from .models import Goods, GoodsCategory


class CategorySerializer01(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class CategorySerializer0202(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class CategorySerializer0201(serializers.ModelSerializer):
    # 通过一级分类获取到二级分类，由于一级分类下有多个二级分类，需要设置many=True
    sub_category = CategorySerializer0202(many=True)

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class CategorySerializer0303(serializers.ModelSerializer):
    '''
    三级目录
    '''

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class CategorySerializer0302(serializers.ModelSerializer):
    sub_category = CategorySerializer0303(many=True)  # 通过二级分类获取三级分类

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class CategorySerializer0301(serializers.ModelSerializer):
    sub_category = CategorySerializer0302(many=True)  # 通过一级分类获取到二级分类，由于一级分类下有多个二级分类，需要设置many=True

    class Meta:
        model = GoodsCategory
        fields = '__all__'


# 获取父级分类
class ParentCategorySerializer0101(serializers.ModelSerializer):
    '''
    一级目录
    '''
    class Meta:
        model = GoodsCategory
        fields = '__all__'


class ParentCategorySerializer0102(serializers.ModelSerializer):
    '''
    二级目录
    '''
    parent_category = ParentCategorySerializer0101()

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class ParentCategorySerializer0103(serializers.ModelSerializer):
    '''
    三级目录
    '''
    parent_category = ParentCategorySerializer0102()

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsSerializer01(serializers.Serializer):
    name = serializers.CharField(max_length=300, required=True)
    shop_price = serializers.FloatField(default=0)
    goods_front_image = serializers.ImageField()

    def create(self, validated_data):
        """
        给定经过验证的数据，创建并返回一个新的“Goods”实例。
        """
        return Goods.objects.create(**validated_data)


# ModelSerializer实现
class GoodsSerializer02(serializers.ModelSerializer):
    category = CategorySerializer01()  # 自定义字段覆盖原有的字段，实例化

    class Meta:
        model = Goods
        # fields = ('id', 'name', 'category', 'shop_price', 'goods_front_image')
        fields = '__all__'
